﻿using System;
using System.Linq;
using context;
using entities;

namespace DataAccessLibrary.DAL
{
    public class AuthenDAO
    {
        private readonly BlueMDataContext _ctx;

        public AuthenDAO()
        {
            _ctx = new BlueMDataContext();
        }

        public string RoleGet(string userName, string password)
        {
            try
            {
                var query =
                    _ctx.Employees.Where(p => p.EmployeeAccount == userName && p.EmployeePassword == password).Select(
                        q => q.EmployeePosition);
                return query.FirstOrDefault();
            }
            catch (Exception)
            {
                return null;
            }
        }

        public bool UserCheck(string userName, string passWord, string position, string serviceName)
        {
            var query =
                _ctx.Employees.Where(
                    p =>
                    p.EmployeeAccount == userName && p.EmployeePassword == passWord &&
                    p.EmployeePosition == position);
            var result = query.Any();
            if (result)
            {
                var employeeLog = new EmployeeLog
                                      {
                                          EmployeeID = query.First().EmployeeID,
                                          LoginTime = DateTime.Now,
                                          ServiceName = serviceName
                                      };
                _ctx.EmployeeLogs.InsertOnSubmit(employeeLog);
                _ctx.SubmitChanges();
                return true;
            }
            return false;
        }

        public bool ChangePassword(string userName, string passWord, string newPassWord)
        {
            
                IQueryable<Employee> query =
                   _ctx.Employees.Where(
                       p =>
                       p.EmployeeAccount == userName && p.EmployeePassword == passWord );
                if (query.Count()==1)
                {
                    Employee emp = query.First();
                    emp.EmployeePassword = newPassWord;
                   _ctx.SubmitChanges();
                    return true;
                }
                throw new Exception("Can not change password");
        }


    }
}